/*
 *  Copyright 2001-2004 The Apache Software Foundation
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */
package ar.uba.fi.posgrado.academy.service.impl;

import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import ar.uba.fi.posgrado.academy.dao.BodyDAO;
import ar.uba.fi.posgrado.academy.model.Body;
import ar.uba.fi.posgrado.academy.service.BodyService;
import ar.uba.fi.posgrado.common.dao.NoSuchEntityException;
import ar.uba.fi.posgrado.common.exception.MissingArgumentException;
import ar.uba.fi.posgrado.common.exception.PosgradoException;
import ar.uba.fi.posgrado.common.exception.PosgradoRuntimeException;
import ar.uba.fi.posgrado.common.exception.RepeatedNameException;
import ar.uba.fi.posgrado.common.model.User;

public class BodyServiceImpl implements BodyService {

	private BodyDAO bodyDAO;
	
	public BodyDAO getBodyDAO() {
		return bodyDAO;
	}

	public void setBodyDAO(BodyDAO bodyDAO) {
		this.bodyDAO = bodyDAO;
	}
	
	@Transactional(readOnly = false, propagation = Propagation.REQUIRED)
	public void create(Body body) throws MissingArgumentException,
			PosgradoException {
		if (StringUtils.isBlank(body.getCode())
				|| StringUtils.isBlank(body.getName())) {
			String mensaje = "El codigo y el nombre son datos obligatorios para guardar un ente";
			throw new MissingArgumentException(mensaje);
		}

		try {
			// Puede ser q el nombre de usuario exista
			this.getBodyDAO().findByCode(body.getCode());

			throw new RepeatedNameException("El ente con codigo " + body.getCode()
					+ " no es valido. Ya existe un ente con ese codigo.");
		} catch (NoSuchEntityException e) {
			// Si entro aca es xq no existia x lo cual esta bien
		}

		this.getBodyDAO().save(body);
	}

	@Transactional(readOnly = false, propagation = Propagation.REQUIRED)
	public void delete(Body t) throws PosgradoRuntimeException,
			PosgradoException {
		this.getBodyDAO().remove(t);
	}

    @Transactional(readOnly = true)
	public List<Body> getAll() throws PosgradoRuntimeException,
			PosgradoException {
		return this.getBodyDAO().findAll();
	}

    @Transactional(readOnly = true)
	public Body getById(Long id) throws PosgradoRuntimeException,
			PosgradoException {
		return (Body) this.getBodyDAO().findById(id);
	}

	@Transactional(readOnly = true)
	public Body getByCode(String code) throws PosgradoRuntimeException,
			PosgradoException {
		return this.getBodyDAO().findByCode(code);
	}

	@Transactional(readOnly = false, propagation = Propagation.REQUIRED)
	public Body update(Body body) throws PosgradoRuntimeException,
			PosgradoException {
		Body toUpdateBody = this.getById(body.getId());

		if (StringUtils.isBlank(body.getCode())
				|| StringUtils.isBlank(body.getName())) {
			String mensaje = "El codigo y el nombre son datos obligatorios para guardar un ente";
			throw new MissingArgumentException(mensaje);
		}

		if (!body.getId().equals(toUpdateBody.getId())) {
			try {
				Body s = this.getById(body.getId());
				if (s.getId() != toUpdateBody.getId()) {
					throw new RepeatedNameException(
							"No se puede actualizar el ente. Ya hay otro ente en el sistema con el id "
									+ body.getId());
				}
			} catch (NoSuchEntityException e) {
				// significa que esta todo bien y puede actualizar el ente
				toUpdateBody.setName(body.getName());
				toUpdateBody.setCode(body.getCode());

				this.getBodyDAO().update(toUpdateBody);
				body = toUpdateBody;
			}
		} else {
			toUpdateBody.setName(body.getName());
			toUpdateBody.setCode(body.getCode());

			this.getBodyDAO().update(toUpdateBody);
			body = toUpdateBody;
		}
		return body;
	}

	/** 
	 * @see ar.uba.fi.posgrado.common.service.GenericService#filter(java.util.List, ar.uba.fi.posgrado.common.model.User)
	 */
	public List<Body> filter(List<Body> list, User user)
			throws PosgradoRuntimeException, PosgradoException {
		return list;
	}

	
	
}
